<template>
  <div class="table-bottom table-gl-w">
    <div class="search-w">
      <FilterTable :max-num="5" :filterItem="filterItem" :isReset="true" @search="searchByVal"> </FilterTable>
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft>
          <a-space>
            <a-button v-if="['draft', 'fail'].includes(props.status)" class="gray-outline" @click="submitAudit">提交审核</a-button>
            <a-button v-if="['draft', 'fail'].includes(props.status)" class="gray-outline" @click="show('editTitleOrDesc')">修改标题和描述</a-button>
            <a-button v-if="['draft', 'fail'].includes(props.status)" class="gray-outline" @click="show('keyWord')">设置关键词</a-button>
            <a-button v-if="['draft', 'fail'].includes(props.status)" class="gray-outline" @click="show('goodsVisibility')">设置可见性</a-button>
            <a-button v-if="['draft', 'fail'].includes(props.status)" class="gray-outline" @click="show('goodsVisualRange')">设置可见范围</a-button>
            <a-button v-if="['draft'].includes(props.status)" class="gray-outline" @click="showCreateShopModal = true">创建商品</a-button>
            <a-button v-if="props.status == 'auditing'" class="gray-outline" @click="check">审核</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table :data="tableData" size="mini" row-key="id" v-model:selected-keys="ids" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" class="table-single-line" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" #cell="{ rowIndex }" :width="50">{{ rowIndex + 1 }}</a-table-column>
              <a-table-column title="图片" #cell="{ record }" :width="60">
                <a-image @click="showBigImg(record)" width="40" height="40" fit="contain" :preview="false" :src="imgUrl(record)" />
              </a-table-column>
              <a-table-column title="店铺" #cell="{ record }" :width="120">
                <TextLimit :rows="1" position="top" :val="record.shopName"></TextLimit>
              </a-table-column>
              <a-table-column title="主体库存SKU" #cell="{ record }" :width="120">
                <TextLimit position="top" :val="$extract(record, 'dataFromRestApi.sku') || '--'"></TextLimit>
              </a-table-column>
              <a-table-column title="分类" #cell="{ record }" :width="120">
                <TextLimit position="top" :val="getCategoryName(record)"></TextLimit>
              </a-table-column>
              <a-table-column title="标题" #cell="{ record }" :width="140">
                <TextLimit position="top" :rows="1" :val="$extract(record, 'dataFromRestApi.name')"></TextLimit>
              </a-table-column>
              <!-- <a-table-column title="简短描述" #cell="{ record }" :width="160">
                <div v-if="$extract(record, 'dataFromRestApi.short_description')" v-html="$extract(record, 'dataFromRestApi.short_description')"></div>
                <TextLimit v-if="$extract(record, 'dataFromRestApi.short_description')" position="top" :val="$extract(record, 'dataFromRestApi.short_description')"></TextLimit>
                <div v-else>--</div>
              </a-table-column> -->
              <a-table-column title="关键词" #cell="{ record }" :width="120">
                <TextLimit position="top" :val="getKeywordName(record) || '--'"></TextLimit>
              </a-table-column>

              <a-table-column title="产品属性" #cell="{ record }" :width="80">
                <productPre :info="record" />
              </a-table-column>

              <a-table-column title="可见性" #cell="{ record }" :width="80">
                {{ visiableMap[$extract(record, 'dataFromRestApi.status')] }}
              </a-table-column>
              <a-table-column title="可见范围" #cell="{ record }" :width="80">
                {{ visiableRangeMap[$extract(record, 'dataFromRestApi.catalog_visibility')] || $extract(record, 'dataFromRestApi.catalog_visibility') }}
              </a-table-column>
              <a-table-column title="类型" #cell="{ record }" :width="80">
                {{ $extract(record, 'dataFromRestApi.type') == 'simple' ? '单体' : '变体' }}
              </a-table-column>
              <a-table-column title="变体库存SKU" #cell="{ record }" :width="100">
                <skuListPopover :data="record" />
              </a-table-column>
              <a-table-column title="售价方式" #cell="{ record }" :width="80">
                {{ showSaleType(record) }}
              </a-table-column>
              <a-table-column title="售价" #cell="{ record }" :width="140">
                <div v-if="showSaleType(record) == '一口价'"></div>
                <div v-else>
                  <div v-for="(item, index) of getMetaDataArr(record)" :key="index">
                    <span>{{ item.quantity }}</span>
                    <span>-</span>
                    <span>{{ item.endNum }}</span>
                    <span>：</span>
                    <span>${{ item.price }}</span>
                  </div>
                </div>
              </a-table-column>
              <a-table-column title="运营" #cell="{ record }" :width="80">
                {{ record.operationUserName ? record.operationUserName : '--' }}
              </a-table-column>
              <a-table-column title="创建时间" #cell="{ record }" :width="140">
                {{ $setTime(record.gmtCreate) }}
              </a-table-column>

              <a-table-column title="失败原因" #cell="{ record }" :width="140" v-if="['fail'].includes(props.status)">
                <TextLimit position="top" :val="record.publishRemark"></TextLimit>
              </a-table-column>

              <a-table-column title="操作" #cell="{ record }" :width="80" fixed="right">
                <a-space>
                  <a-button type="text" v-if="['auditing', 'success'].includes(props.status)" @click="toDetail(record)">详情</a-button>
                  <a-button type="text" @click="edit(record)" v-if="['draft', 'fail'].includes(props.status)">编辑</a-button>
                  <a-button type="text" style="color: red" @click="del(record.id)" v-if="['draft', 'fail'].includes(props.status)">删除</a-button>
                </a-space>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>

  <!-- 新建商品 -->
  <createShop v-if="showCreateShopModal" :shopList="shopList" v-model="showCreateShopModal" @save="resetAndRefreshList" :shopId="searchValue.shopIdList" />
  <!-- 批量修改标题或者描述 -->
  <batchEditTitleOrDesc menuType="publish" v-if="showBatchEditTitleOrDescModal" v-model="showBatchEditTitleOrDescModal" :shopId="searchValue.shopIdList" :list="selDataList" @save="resetAndRefreshList" />
  <!-- 批量修改关键词 -->
  <batchSetKeyword menuType="publish" v-if="showBatchSetKeywordModal" v-model="showBatchSetKeywordModal" :list="selDataList" :shopId="searchValue.shopIdList" @save="resetAndRefreshList" />
  <!-- 批量设置可见性和可见范围 -->
  <batchSetVisibleOrRange menuType="publish" v-if="showBatchSetVisibleOrRangeModal" v-model="showBatchSetVisibleOrRangeModal" :type="batchSetVisibleOrRangeType" :shopId="searchValue.shopIdList" :list="selDataList" @save="resetAndRefreshList" />
  <!-- 审核 -->
  <checkPublishData v-if="showCheckModal" v-model="showCheckModal" :ids="ids" @save="resetAndRefreshList" />
  <!-- 图片查看 -->
  <a-image-preview-group v-model:visible="visible" v-model:current="current" infinite :srcList="previewList" />
  <!-- 详情 -->
  <publishDetailInfo v-if="showPublishDetailInfoModal" v-model="showPublishDetailInfoModal" :id="id" />
</template>

<script lang="ts" setup>
  import { onMounted, ref, watch, nextTick, onUnmounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { Message, Modal } from '@arco-design/web-vue'
  // import { findShopPageByParam } from '@/api/system'
  import { listAllCategoryTreeByShopId, tagRollPage, versionRollPage, versionBatchDelete, versionBatchSubmitAudit, versionBatchAudit, listAllUserWordPressShop } from '@/api/product'
  import { getOrganizesUser } from '@/api/system'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import skuListPopover from './components/skuListPopover.vue'
  import productPre from './components/productPre.vue'
  import createShop from './components/createShop.vue'
  import batchEditTitleOrDesc from './components/batchEditTitleOrDesc.vue'
  import batchSetKeyword from './components/batchSetKeyword.vue'
  import batchSetVisibleOrRange from './components/batchSetVisibleOrRange.vue'
  import checkPublishData from './components/checkPublishData.vue'
  import publishDetailInfo from './publishDetailInfo.vue'
  const sessionStorageObj = JSON.parse(sessionStorage.getItem('puglishPageNation') || '{}')
  const visiableMap = {
    publish: '公开',
    private: '私密',
    draft: '草稿',
  }
  const visiableRangeMap = {
    catalog: '仅商品页',
    visible: '商品页和搜素结果页',
    search: '仅搜素结果页',
    hidden: '隐藏',
  }
  const props = defineProps(['status'])
  const route = useRouter()

  let pageNation = ref({ total: 100, pageNum: sessionStorageObj.pageNum || 1, pageSize: sessionStorageObj.pageSize || 20 })
  let loading = ref(false)
  let showCheckModal = ref(false)
  let showPublishDetailInfoModal = ref(false)
  let ids = ref([])
  let id = ref()
  let tableData = ref([])
  let shopList = ref([]) // 店铺列表
  let searchValue: any = ref({})

  let selDataList: any = ref([])

  let visible = ref(false)
  let current = ref(0)
  let previewList = ref([])
  let showCreateShopModal = ref(false)
  let showBatchEditTitleOrDescModal = ref(false)
  let showBatchSetKeywordModal = ref(false)
  let showBatchSetVisibleOrRangeModal = ref(false)
  let batchSetVisibleOrRangeType = ref('')
  const filterItem: any = ref([
    {
      key: 'shopIdList',
      label: '店铺',
      value: ref(),
      type: 'select',
      width: 160,
      optionItems: [],
      attrs: {
        allowClear: false,
        // multiple: true,
        // 'max-tag-count': 1,
      },
    },
    {
      type: 'input_keyword',
      key: 'name',
      keyItems: [
        { label: '标题', value: 'name' },
        { label: '简短描述', value: 'description' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '标题',
      width: 180,
    },
    {
      type: 'input_keyword_type',
      key: 'dataFromRestApi.sku',
      keyItems: [
        { label: '主体库存SKU', value: 'dataFromRestApi.sku' },
        { label: '变体库存SKU', value: 'variationList.dataFromRestApi.sku' }, //未定
      ],
      keyWidth: '130',
      value: ref(),
      placeholder: '请输入',
      label: '主体库存SKU',
      width: 200,
      isMultiple: true,
    },
    {
      key: 'operationUserIdList',
      label: '运营',
      value: ref(),
      type: 'select',
      width: 180,
      optionItems: [],
      attrs: {
        'allow-clear': true,
      },
    },
    {
      key: 'productApiStatusList',
      label: '可见性',
      value: ref(),
      type: 'select',
      width: '100%',
      optionItems: [
        { label: '公开', value: 'publish' },
        { label: '私密', value: 'private' },
      ],
      attrs: {
        'allow-clear': true,
      },
    },
    {
      key: 'catalogVisibilityList',
      label: '可见范围',
      value: ref(),
      type: 'select',
      width: '100%',
      optionItems: [
        { label: '可见', value: 'visible' },
        { label: '搜索', value: 'search' },
        { label: '隐藏', value: 'hidden' },
      ],
    },
    {
      type: 'cascader',
      key: 'categoryIdList',
      optionItems: [],
      keyWidth: '120',
      value: ref(),
      placeholder: '商品分类',
      label: '类目',
      width: '100%',
      isMultiple: true,
    },
    {
      key: 'tagIdList',
      label: '标签',
      value: ref(),
      type: 'select',
      width: '100%',
      optionItems: [],
    },
    // {
    //   key: 'taskType',
    //   label: '类型',
    //   value: ref(),
    //   type: 'select',
    //   width: '100%',
    //   optionItems: [
    //     { label: '单体', value: '单体' },
    //     { label: '变体', value: '变体' },
    //   ],
    //   attrs: {
    //     'allow-clear': true,
    //   },
    // },
    // {
    //   key: 'taskType',
    //   label: '产品来源',
    //   value: ref(),
    //   type: 'select',
    //   width: '100%',
    //   optionItems: [
    //     { label: '自营', value: '自营' },
    //     { label: '1688', value: '1688' },
    //     { label: 'Amazon', value: 'Amazon' },
    //     { label: '梅陇在线', value: '梅陇在线' },
    //     { label: '其他', value: '其他' },
    //   ],
    // },
    {
      key: 'metaDataList',
      label: '售价方式',
      value: ref(),
      type: 'select',
      width: '100%',
      optionItems: [
        { label: '一口价', value: 'disable' },
        { label: '阶梯价', value: 'override' },
      ],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [{ label: '创建时间', value: 'gmtCreate' }],
      keyWidth: '110',
      label: '创建时间',
      value: ref(),
      width: 300,
    },
  ])

  // 搜索
  const searchByVal = (info: any) => {
    // 修改店铺的时候获取分类数据和标签数据
    if (info.shopIdList != searchValue.value.shopIdList) {
      searchValue.value.shopIdList = info.shopIdList
      filterItem.value[0].value = info.shopIdList
      nextTick(() => {
        getCategory()
        getTagList()
      })
    }
    searchValue.value = info
    getList()
  }
  // 分页
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  // 显示弹框
  const show = (type: string) => {
    selDataList.value = []

    if (!ids.value[0]) {
      return Message.error('请选择要设置的数据')
    }

    ids.value.forEach((e: string) => {
      let item = tableData.value.find((el: any) => el.id == e)
      selDataList.value.push(item)
    })

    switch (type) {
      case 'editTitleOrDesc':
        showBatchEditTitleOrDescModal.value = true
        break
      case 'keyWord':
        showBatchSetKeywordModal.value = true
        break
      case 'goodsVisibility':
        batchSetVisibleOrRangeType.value = 'goodsVisibility'
        showBatchSetVisibleOrRangeModal.value = true
        break
      case 'goodsVisualRange':
        batchSetVisibleOrRangeType.value = 'goodsVisualRange'
        showBatchSetVisibleOrRangeModal.value = true
        break
    }
  }

  // 获取类目
  const getCategory = async () => {
    const res: any = await listAllCategoryTreeByShopId({ shopId: searchValue.value.shopIdList })
    let arr = res.data
    setNewTreeData(arr)
    filterItem.value[6].optionItems = arr
  }

  const setNewTreeData = (data: any) => {
    data.forEach((item: any) => {
      item.name = item.dataFromRestApi.name
      item.value = item.dataFromRestApi.id
      if (!item.children[0]) item.children = null
      if (item.children) {
        setNewTreeData(item.children)
      }
    })
  }

  // 获取标签
  const getTagList = async () => {
    const res: any = await tagRollPage({ shopIdList: [searchValue.value.shopIdList], pageSize: 9999999 })
    let arr = res?.data?.list || []
    filterItem.value[7].optionItems = arr.map((e: any) => {
      e.label = e.dataFromRestApi.name
      e.value = e.id
      return e
    })
  }

  // 图片
  const imgUrl = (info: any) => {
    let arr = info.dataFromRestApi?.images || []
    return arr[0]?.src || ''
  }

  const del = (id: string) => {
    Modal.error({
      title: '删除任务',
      content: '请再次确认是否需要删除',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const res: any = await versionBatchDelete({ idList: [id] })
        if (res.code == 'SUCCESS') {
          Message.success('删除成功')
          ids.value = []
          getList()
        }
      },
    })
  }

  // 获取店铺信息
  const getShopLsit = async () => {
    let params = {
      pageSize: 999999,
      platform: 'wooCommerce',
    }
    const res: any = await listAllUserWordPressShop(params)
    if (res) {
      let arr = res.data || []
      shopList.value = arr
      filterItem.value[0].optionItems = arr.map((item: any) => {
        item.label = item.shopName
        item.value = item.id
        return item
      })
      filterItem.value[0].value = arr[0].id
      searchValue.value.shopIdList = arr[0].id
    }
  }

  const getList = async () => {
    let params: any = {
      ...searchValue.value,
      needCount: true,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
      statusList: [props.status],
    }

    if (params.shopIdList) params.shopIdList = params.shopIdList.split(',')

    if (params.metaDataList) {
      params.metaDataList = [{ key: 'wpcpq_enable', value: searchValue.value.metaDataList }]
    }
    // 可见范围传数组
    if (params.catalogVisibilityList) {
      params.catalogVisibilityList = params.catalogVisibilityList.split(',')
    } else {
      delete params.catalogVisibilityList
    }
    // 分类搜索也是传数组
    if (params.categoryIdList) {
      params.categoryIdList = params.categoryIdList.split(',')
    } else {
      delete params.categoryIdList
    }
    if (params.productApiStatusList) {
      params.productApiStatusList = params.productApiStatusList.split(',')
    } else {
      delete params.productApiStatusList
    }

    if (params.tagIdList) {
      params.tagIdList = params.tagIdList.toString().split(',')
    } else {
      delete params.tagIdList
    }
    if (params.operationUserIdList) {
      params.operationUserIdList = params.operationUserIdList.split(',')
    } else {
      delete params.operationUserIdList
    }

    if (params.startDate) {
      params.startDate = `${params.startDate} 00:00:00`
      params.endDate = `${params.endDate} 23:59:59`
    } else {
      delete params.startDate
      delete params.endDate
    }

    loading.value = true
    const res: any = await versionRollPage(params)
    loading.value = false
    pageNation.value.total = res.data.total || []
    let resultArr = res.data.list || []
    tableData.value = resultArr

    console.log(tableData.value, 'tableData.value')
  }

  const resetAndRefreshList = () => {
    pageNation.value.pageNum = 1
    ids.value = []
    selDataList.value = []
    getList()
  }

  const getCategoryName = (info: any) => {
    let arr = info.dataFromRestApi?.categories || []
    return arr.map((e: any) => e.name).join('，')
  }

  const getKeywordName = (info: any) => {
    let arr = info.dataFromRestApi?.tags || []
    return arr.map((e: any) => e.name).join('，')
  }

  const showSaleType = (data: any) => {
    let arr = data?.dataFromRestApi?.meta_data || []
    if (arr[0]) {
      let item = arr.find((e: any) => e.key == 'wpcpq_enable')
      return item && item.value == 'disable' ? '一口价' : '阶梯价'
    } else {
      return '--'
    }
  }

  const showBigImg = (data: any) => {
    let arr = data?.dataFromRestApi?.images || []
    previewList.value = arr.map((e: any) => e.src)
    current.value = 0
    visible.value = true
  }

  const getMetaDataArr = (data: any) => {
    let resArr = []
    let arr = data?.dataFromRestApi?.meta_data || []
    if (arr[0]) {
      let item = arr.find((e: any) => e.key == 'wpcpq_prices')?.value || {}
      if (item.length > 3) resArr = JSON.parse(item).tiers
    }
    return resArr
  }

  // 提交审核
  const submitAudit = () => {
    if (!ids.value[0]) {
      return Message.error('请选择要提交审核的数据')
    }
    Modal.info({
      title: '提交审核',
      content: '是否提交审核',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const res: any = await versionBatchSubmitAudit({ idList: ids.value })
        if (res.code == 'SUCCESS') {
          Message.success('提交审核成功')
          getList()
          ids.value = []
        }
      },
    })
  }

  // 审核
  const check = () => {
    if (!ids.value[0]) {
      return Message.error('请选择要审核的数据')
    }

    showCheckModal.value = true
    // Modal.info({
    //   title: '审核',
    //   content: '是否通过审核',
    //   titleAlign: 'start',
    //   cancelText: '取消',
    //   hideCancel: false,
    //   onOk: async () => {
    //     const res: any = await versionBatchAudit({ agree: true, idList: ids.value })
    //     if (res.code == 'SUCCESS') {
    //       Message.success('审核成功')
    //       ids.value = []
    //       getList()
    //     }
    //   },
    // })
  }

  // 编辑刊登
  const edit = (info: any) => {
    let obj = {
      pageSize: pageNation.value.pageSize,
      pageNum: pageNation.value.pageNum,
    }

    sessionStorage.setItem('puglishPageNation', JSON.stringify(obj))

    route.push({
      path: '/wordPress/publish/editPublishData',
      query: {
        id: info.id,
      },
    })
  }
  // 详情
  const toDetail = (info: any) => {
    id.value = info.id
    showPublishDetailInfoModal.value = true
    // route.push({
    //   path: '/wordPress/publish/publishDetailInfo',
    //   query: {
    //     id: info.id,
    //   },
    // })
  }

  const getUSerList = async () => {
    let params = {
      depart: false,
      pageNum: 1,
      pageSize: 100000,
    }
    const res: any = await getOrganizesUser(params)
    let arr = res?.data?.records || []
    filterItem.value[3].optionItems = arr.map((e: any) => {
      e.label = e.userName
      e.value = e.id
      return e
    })
    // userList.value = res?.data?.records || []
  }

  onMounted(async () => {
    getUSerList()
    await getShopLsit()
    await getCategory()
    await getTagList()
    await getList()
  })

  watch(
    () => props.status,
    () => {
      pageNation.value.pageNum = 1
      getList()
    }
  )
</script>

<style lang="less" scoped>
  .table-bottom {
    height: calc(100vh - @menuAndTabHeight);
    .search-w {
      width: 100%;
      background-color: white;
      padding: 10px 0 1px 0;
      box-sizing: border-box;
    }
  }
</style>
